package integral

import (
	"context"
	// "fmt"
	"strings"

	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/user/model"
	"mall/service/user/rpc/internal/svc"
	"mall/service/user/rpc/types/user"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetIntegralExchangeProductLogListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetIntegralExchangeProductLogListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetIntegralExchangeProductLogListLogic {
	return &GetIntegralExchangeProductLogListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetIntegralExchangeProductLogListLogic) GetIntegralExchangeProductLogList(in *user.BaseListReq) (*user.IntegralTransactionLogListResp, error) {
	logx.Infof("GetIntegralExchangeProductLogList : %+v ", in)
	// Limit:10 Preload:\"userIntegralTransactionLog:Id,UserId,ProductId,ProductName,ProductCode,SkuId,SkuCode,Sku,Url,OrderId,OrderSn,Point,Amount,Status,CreatedAt\" EagerLoad:\"userIntegralTransactionLog:total\" Filter:\"UserId,equalTo:10021\" VisitorId:10021 PlatformId:1 ","level":"info"}

	if in.Filter == nil || len(*in.Filter) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	preloadMap, eagerLoadMap := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)
	// logrus.Info(fmt.Sprintf("GetIntegralExchangeProductLogList preloadMap: %+v", preloadMap))
	// map[total:[] userIntegralTransactionLog:[Id UserId ProductId ProductCode ProductName SkuId SkuCode Sku Url OrderId OrderSn Points Amount Status CreatedAt UpdatedAt]]

	// logrus.Info(fmt.Sprintf("GetIntegralExchangeProductLogList eagerLoadMap: %+v", eagerLoadMap))
	// map[userIntegralTransactionLog:[total]]

	userIntegralTransactionEntityName := model.RpcEntityNames.UserIntegralTransactionLog
	if _, ok := model.RpcEntityPreloadMap[userIntegralTransactionEntityName]; !ok {
		return &user.IntegralTransactionLogListResp{}, nil
	}

	userIntegralTransactionRepositoryName := model.RepositoryNames.UserIntegralTransactionLog
	columnMap, ok := model.RepositoryPreloadMap[userIntegralTransactionRepositoryName]
	if !ok {
		return &user.IntegralTransactionLogListResp{}, nil
	}

	var selectCols []string
	if preloadFields, ok := preloadMap[userIntegralTransactionEntityName]; ok {
		selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
	}

	filterMap := modelx.ParseFilter(in.Filter, columnMap)
	// logrus.Info(fmt.Sprintf("GetIntegralExchangeProductLogList filterMap: %+v", filterMap))
	// map[user_id:map[equalTo:[10021]]]
	if filterMap == nil {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	orderBy := modelx.ParseSorter(in.Sorter, columnMap)
	// logrus.Info(fmt.Sprintf("GetIntegralExchangeProductLogList orderBy: %s", orderBy))
	if len(orderBy) == 0 {
		orderBy = model.UserTaskLogColumns.ID + " DESC"
	}

	res, count, err := l.svcCtx.CurrentUser.GetIntegralTransactionLog(l.ctx, model.M{
		"offset":  in.Offset,
		"limit":   in.Limit,
		"orderBy": orderBy,
		"select":  strings.Join(selectCols, ","),
	}, 2, filterMap)
	if err != nil {
		return nil, err
	}

	hasNextPage, hasPreviousPage := modelx.ParseCount(count)
	resp := &user.IntegralTransactionLogListResp{
		HasNextPage:     &hasNextPage,
		HasPreviousPage: &hasPreviousPage,
	}

	var total int64
	if len(res) > 0 {
		if eagerLoadEntities, ok := eagerLoadMap[userIntegralTransactionEntityName]; ok {
			for _, entity := range eagerLoadEntities {
				if entity == "total" {
					_, total, err = l.svcCtx.CurrentUser.GetIntegralTransactionLog(l.ctx, model.M{}, 0, filterMap)
					if err != nil {
						total = 0
					}
					continue
				}
			}
		}

		for _, v := range res {
			resp.List = append(resp.List, &user.IntegralTransactionLogInfo{
				Id:          &v.ID,
				UserId:      &v.UserID,
				ProductId:   &v.ProductID,
				ProductCode: &v.ProductCode,
				ProductName: &v.ProductName,
				SkuId:       &v.SkuID,
				SkuCode:     &v.SkuCode,
				Sku:         &v.Sku,
				Url:         &v.URL,
				OrderId:     &v.OrderID,
				OrderSn:     &v.OrderSN,
				Points:      &v.Points,
				Amount:      &v.Amount,
				Status:      pointy.GetPointer(uint32(v.Status)),
				CreatedAt:   pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt:   pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
			})
		}
	}

	resp.Total = uint64(total)

	return resp, nil
}
